package com.ruoyi.system.service.impl;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.Sftp;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.Seq;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CertificateInfoMapper;
import com.ruoyi.system.domain.CertificateInfo;
import com.ruoyi.system.service.ICertificateInfoService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户证件资料Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-11
 */
@Service
public class CertificateInfoServiceImpl implements ICertificateInfoService {
    public static final String ERROR = "文件上传失败";
    public static final String JPG = "jpg";
    public static final String PNG = "png";
    private Logger logger = LoggerFactory.getLogger(CertificateInfoServiceImpl.class);
    @Autowired
    private CertificateInfoMapper certificateInfoMapper;

    /**
     * 查询用户证件资料
     *
     * @param id 用户证件资料主键
     * @return 用户证件资料
     */
    @Override
    public CertificateInfo selectCertificateInfoById(Long id) {
        return certificateInfoMapper.selectCertificateInfoById(id);
    }

    /**
     * 查询用户证件资料列表
     *
     * @param certificateInfo 用户证件资料
     * @return 用户证件资料
     */
    @Override
    public List<CertificateInfo> selectCertificateInfoList(CertificateInfo certificateInfo) {
        return certificateInfoMapper.selectCertificateInfoList(certificateInfo);
    }

    /**
     * 新增用户证件资料
     *
     * @param certificateInfo 用户证件资料
     * @return 结果
     */
    @Override
    public int insertCertificateInfo(CertificateInfo certificateInfo) {
        List<String> paths = new ArrayList<>();
        List<String> names = new ArrayList<>();
        try {
            for (MultipartFile multipartFile : certificateInfo.getFiles()) {
                InputStream is = multipartFile.getInputStream();
                String path = FileUploadUtils.upload(multipartFile);
                paths.add(path);
                names.add(multipartFile.getOriginalFilename());
                String fileName = StringUtils.format("{}_{}.{}",
                        FilenameUtils.getBaseName(multipartFile.getOriginalFilename()),
                        Seq.getId(Seq.uploadSeqType), FileUploadUtils.getExtension(multipartFile));

                //上传ftp(图片的话 添加水印并压缩)
                //匿名登录（无需帐号密码的FTP服务器）默认被动模式
//                Ftp ftp = new Ftp("172.0.0.1", 22, "", "");
                Sftp ftp = new Sftp("10.18.1.18", 22, "ibp", "sanss123");
                //进入远程目录
                String catalog = "/home/ibp/work/upload";
                ftp.cd(catalog);
                //上传本地文件
                if (path.contains(JPG) || path.contains(PNG)) {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    //添加水印
                    ImgUtil.pressText(
                            is,
                            os,
                            //文字
                            "阿尔卡特SANSS", Color.WHITE,
                            //字体
                            new Font("黑体", Font.BOLD, 100),
                            //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                            0,
                            //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                            0,
                            //透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                            0.6f
                    );
                    //如果是png需要转为jpg
                    if (path.contains(PNG)) {
                        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
                        ByteArrayOutputStream jpg = new ByteArrayOutputStream();
                        ImgUtil.convert(inputStream, fileName, jpg);
                    }
                    //压缩
                    InputStream inputStream2 = new ByteArrayInputStream(os.toByteArray());
                    ByteArrayOutputStream ys = new ByteArrayOutputStream();
                    Img.from(inputStream2)
                            //压缩比率
                            .setQuality(0.8)
                            .write(ys);
                    //上传
                    InputStream inputStream = new ByteArrayInputStream(ys.toByteArray());
                    ftp.upload(catalog, fileName, inputStream);
                } else {
                    ftp.upload(catalog, fileName, is);
                }
                //关闭连接
                ftp.close();
            }
        } catch (IOException e) {
            logger.error(ERROR);
            throw new ServiceException(ERROR);
        }
        for (int i = 0; i < paths.size(); i++) {
            CertificateInfo cf = new CertificateInfo();
            cf.setStatus("成功");
            cf.setUserId(SecurityUtils.getUserId());
            cf.setFilePath(paths.get(i));
            cf.setFileName(names.get(i));
            certificateInfoMapper.insertCertificateInfo(cf);
        }
        return paths.size();
    }

    /**
     * 修改用户证件资料
     *
     * @param certificateInfo 用户证件资料
     * @return 结果
     */
    @Override
    public int updateCertificateInfo(CertificateInfo certificateInfo) {
        certificateInfo.setUpdateTime(DateUtils.getNowDate());
        return certificateInfoMapper.updateCertificateInfo(certificateInfo);
    }

    /**
     * 批量删除用户证件资料
     *
     * @param ids 需要删除的用户证件资料主键
     * @return 结果
     */
    @Override
    public int deleteCertificateInfoByIds(Long[] ids) {
        return certificateInfoMapper.deleteCertificateInfoByIds(ids);
    }

    /**
     * 删除用户证件资料信息
     *
     * @param id 用户证件资料主键
     * @return 结果
     */
    @Override
    public int deleteCertificateInfoById(Long id) {
        return certificateInfoMapper.deleteCertificateInfoById(id);
    }
}
